package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 调用与当前类Test5所在同一个包中被注解@AutoRunClass标注的类中那些被注解
 * @AutoRunMethod标注的方法
 *
 */
public class Test5 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir=new File(Test5.class.getResource(".").toURI());
        String packname=Test5.class.getPackage().getName();
        System.out.println(packname);

        File[] subs=dir.listFiles(f ->f.getName().endsWith(".class"));
        for(File sub:subs){
            String fileName= sub.getName();
            String className=fileName.substring(0,fileName.indexOf("."));
            Class cls=Class.forName(packname+"."+className);
           if(cls.isAnnotationPresent(AutoRunClass.class)){
               System.out.println(className+":被标注了");
               Object obj=cls.newInstance();

               Method[] methods = cls.getDeclaredMethods();
               for(Method method:methods){
                   if(method.isAnnotationPresent(AutoRunMethod.class)){
                       System.out.println(method.getName()+":被标注了");
                       method.invoke(obj);
                   }
               }

           }
        }

    }
}
